package com.lagou.rocketmq.service;


import com.lagou.rocketmq.dao.GoodDao;
import com.lagou.rocketmq.dao.OrdersDao;
import com.lagou.rocketmq.pojo.Orders;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Service
public class OrdersService {

    @Resource
    private GoodDao goodDao;
    @Resource
    private OrdersDao ordersDao;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Transactional
    public void placeOrder(int userId, int goodId) {
        int result = goodDao.inventorySubById(goodId);
        if (result != 1) {
            throw new RuntimeException("下单失败");
        }
        Orders orders = new Orders();
        orders.setGoodId(goodId);
        orders.setUserId(userId);
        orders.setState(0);
        ordersDao.save(orders);
        rocketMQTemplate.syncSend("topic-1:delay",
                MessageBuilder.withPayload(orders.getId()).build(),2000,7);
    }

    @Transactional
    public void pay(int ordersId) {
        Orders orders = new Orders();
        orders.setId(ordersId);
        orders.setState(1);
        ordersDao.save(orders);
    }

}
